﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace ipswitch
{
    class NetworkSet
    {
        public static void SetStatic(IPConfig ip_config)
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                //设置ip地址和子网掩码
                inPar = mo.GetMethodParameters("EnableStatic");                
                inPar["IPAddress"] = new string[] { ip_config.ip };// 1.备用 2.IP
                
                inPar["SubnetMask"] = new string[] { ip_config.mask };
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                //设置网关地址
                inPar = mo.GetMethodParameters("SetGateways");                
                inPar["DefaultIPGateway"] = new string[] { ip_config.gateway }; // 1.网关;2.备用网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);                
                
                break;
            }
        }

        public static void SetDHCP()
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"])
                    continue;
                //重置DNS为空
                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                //开启DHCP
                mo.InvokeMethod("EnableDHCP", null);
            }
        }
    }

}
